<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Ruby Constants: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
<meta name="keywords" content="ruby constants,ruby study notes,free ruby programming guide,ruby guide,free ruby programming course,best ruby guide,ruby tutorials,ruby tutorial,learn ruby,ruby,ruby on rails,ruby rails,ruby learning,ruby tutoring,learning ruby,ruby programming,ruby on rails development,ruby training" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/ruby_constants.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>

<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Learning Ruby site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Ruby Constants</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_self.html">&lt;Ruby Self | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_socket_programming.html">Socket Programming &gt;</a>
                  </strong>
                </p>

                <p>A Ruby constant is like a variable, except that its value is supposed to remain constant for the duration of the program. The Ruby interpreter does not actually enforce the constancy of constants, but it does issue a warning if a program changes the value of a constant (as shown in this trivial example) - <strong>p054constwarn.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p054constwarn.rb
                A_CONST = 10
                A_CONST = 20
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Produces a warning:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                p054constwarn.rb:3: warning: already initialized constant A_CONST
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Lexically, the names of constants look like the names of local variables, except that they begin with a capital letter. By convention, most constants are written in all uppercase with underscores to separate words, LIKE_THIS. Ruby class and module names are also constants, but they are conventionally written using initial capital letters and camel case, LikeThis.</p>

                <p>Note that constants do not exist until a value is actually assigned to them.</p>

                <p>Although constants should not be changed, you can <em>modify</em> the internal states of the objects they reference, as seen in <strong>p055constalter.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p055constalter.rb
                A_CONST = "Doshi"
                B_CONST = A_CONST
                A_CONST[0] = "J" # alter string referenced by constant
                puts A_CONST # displays Joshi
                puts B_CONST # also displays Joshi
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p class="post-note">
                <strong>IN RAILS</strong>: You can find examples of this kind of operation (modify) in the Rails source code, where constants figure prominently and the objects they represent undergo fairly frequent changes.</p>

                <p><strong>Note:</strong></p>

                <ul>
                  <li>Constants defined within a class or module may be accessed anywhere within the class or module.</li>
                  <li>Outside the class or module, they may be accessed using the scope operator, <strong>::</strong> prefixed by an expression that returns the appropriate class or module.</li>
                  <li>Constants defined outside any class or module may be accessed as it is or by using the scope operator with no prefix.</li>
                  <li>Constants may <em>not</em> be defined in methods.</li>
                  <li>Constants may be added to existing classes and modules from the outside by using the class or module name and the scope operator before the constant name.</li>
                </ul>

                <p>The program <strong>p056const.rb</strong> shows all of this:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                OUTER_CONST = 99

                class Const
                    def get_const
                      CONST
                    end
                    CONST = OUTER_CONST + 1
                end

                puts Const.new.get_const
                puts Const::CONST
                puts ::OUTER_CONST
                puts Const::NEW_CONST = 123
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Another elaborate example on own methods in a class is <strong>p057mymethods2.rb</strong> In this example we shall also see how to write a class method.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p057mymethods2.rb
                # variables and methods start lowercase
                $glob = 5             # global variables start with $
                class TestVar         # class name constant, start uppercase
                 @@cla = 6            # class variables start with @@
                 CONST_VAL = 7        # constant style, all caps, underscore
                 def initialize(x)    # constructor
                  @inst = x           # instance variables start with @
                  @@cla += 1          # each object shares @@cla
                 end
                 def self.cla         # class method, getter
                  @@cla
                 end
                 def self.cla=(y)     # class method, setter, also TestVar.
                  @@cla = y
                 end
                 def inst             # instance method, getter
                  @inst
                 end
                 def inst=(i)         # instance method, setter
                  @inst = i
                 end
                end
                puts $glob
                test = TestVar.new(3) # calls constructor
                puts TestVar.cla      # calls getter
                puts test.inspect     # gives object ID and instance vars
                TestVar.cla = 4       # calls setter
                test.inst=8           # calls setter
                puts TestVar.cla
                puts test.inst        # calls getter
                other = TestVar.new(17)
                puts other.inspect
                puts TestVar.cla
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <h3>Summary</h3>

                <p>I have listed down all the <strong><a href="/satishtalim/ruby_summary9.html">important points</a></strong> you need to remember after you have completed the following topics: <a href="/satishtalim/object_serialization.html">Object Serialization</a>, <a href="/satishtalim/modules_mixins.html">Modules/Mixins</a>, <a href="/satishtalim/ruby_self.html">Self</a>, <a href="/satishtalim/ruby_constants.html">Constants</a>.</p>

                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/titles/ruby3/programming-ruby-3">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_self.html">&lt;Ruby Self | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_socket_programming.html">Socket Programming &gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">
            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>

</div>

<!-- footer ends here -->

<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->

</body>
</html>
